package com.meixiang.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cookie.store.MemoryCookieStore;
import com.lzy.okhttputils.model.HttpHeaders;
import com.meixiang.entity.EvaluateGradle;
import com.meixiang.entity.account.UserInfo;
import com.meixiang.global.Config;
import com.meixiang.global.apiConfig;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.Session;
import com.meixiang.util.SharedPreferencesSession;
import com.meixiang.view.wheel.mode.ProvinceModel;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.imkit.RongIM;

/**
 * 作者：黑哥 on 2016/3/29 10:09
 */
public class MXApplication extends MultiDexApplication {
    private String TAG = this.getClass().getSimpleName();
    //得到上下文
    private static Context context;
    public static MXApplication mApp;
    //存储数据
    private Session session;
    //activity的集合用于添加或关闭activity
    public List<Activity> mAcitivity;

    private UserInfo user;

    private static final int TIME_OUT = 60000;//1分钟

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        mApp = this;
        this.session = new SharedPreferencesSession(this);
        initImageLoader();
        OkHttpUtils.init(this);
        OkHttpUtils
                .getInstance()
                .addCommonHeaders(getHeader())
                .debug("http")
                .setCookieStore(new MemoryCookieStore())//cookie使用内存缓存（app退出后，cookie消失）
                .setConnectTimeout(TIME_OUT)
                .setReadTimeOut(TIME_OUT)
                .setWriteTimeOut(TIME_OUT);
        /**
         * OnCreate 会被多个进程重入，这段保护代码，确保只有您需要使用 RongIM 的进程和 Push 进程执行了 init。
         * io.rong.push 为融云 push 进程名称，不可修改。
         */
        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext())) ||
                "io.rong.push".equals(getCurProcessName(getApplicationContext()))) {
            /**
             * IMKit SDK调用第一步 初始化
             */
            RongIM.init(this);
        }
        /**bug检测初始化*/
         CrashReport.initCrashReport(getApplicationContext(), "c7e81598b7", false);

        //检查内存泄漏
        LeakCanary.install(this);
    }

    /**
     * 请求头信息
     *
     * @return
     */
    public static HttpHeaders getHeader() {
        HttpHeaders headers = new HttpHeaders();
        headers.put("jsessionid", MXApplication.mApp.getSession().get("jsessionid"));
        headers.put("fundSessionId", MXApplication.mApp.getSession().get("fundSessionId"));
//
        return headers;
    }

    private void initImageLoader() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)    //缓存在内存
                .cacheOnDisk(true)      //缓存至本地
//              .showImageOnFail(R.mipmap.icon_80)
                .build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .diskCache(new UnlimitedDiscCache(new File(Environment.getExternalStorageDirectory() + File.separator + Config.base_data_path + File.separator + Config.images_cache_path)))
                .defaultDisplayImageOptions(options)
                .diskCacheSize(1024 * 1024 * 100)
                .build();
        ImageLoader.getInstance().init(config);
    }

    /**
     * 添加activity
     */
    public void AddActivity(Activity activity) {
        if (mAcitivity == null) {
            mAcitivity = new ArrayList<Activity>();
        }
        mAcitivity.add(activity);
    }

    /**
     * 移除activity
     */
    public void RemoveActivity() {
        if (mAcitivity != null&&mAcitivity.size()>0) {
            for (int i = 0; i < mAcitivity.size(); i++) {
                mAcitivity.get(i).finish();
            }
            mAcitivity.clear();
        }
    }

    //得到
    public Session getSession() {
        return session;
    }

    //设置
    public void setSession(Session session) {
        this.session = session;
    }

    // 存储数据比较
    public boolean sessionEqual(String key, String cVal) {
        return this.session.get(key) != null
                && this.session.get(key).equals(cVal);
    }

    @SuppressLint("NewApi")
    public boolean hasLogin() {
        if (TextUtils.isEmpty(MXApplication.mApp.getSession()
                .get("jsessionid"))) {//token
            return false;
        } else {
            return true;
        }
    }

    // 退出清空session
    public void logout() {
        Map<String, String> vals = new HashMap<String, String>();
//        vals.put("TOKEN", "");
        vals.put("jsessionid", "");
       /* vals.put("avatarImg", "");
        vals.put("userPhone", "");*/
        this.session.set(vals);
        clearUser();
        user = null;
    }

    public void fundLogout() {
        Map<String, String> vals = new HashMap<String, String>();
        vals.put("fundSessionId","");
        getHeader().remove("fundSessionId");
        this.session.set(vals);
    }

    //清空token
    public void removeToken() {
        Map<String, String> vals = new HashMap<String, String>();
        vals.put("token", "");
        this.session.set(vals);
    }

    // 依据key value 存储数据
    public void setSessionVal(String key, String value) {
        this.session.set(key, value);
    }


    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return 进程号
     */
    public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {

            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public UserInfo getUser() {
        if (user == null) {
            return recoverUser();
        }
        return user;
    }

    public void setUser(UserInfo netUser) {
        user = netUser;
        if (user != null) {
            saveUser(user);
        }
    }

    private UserInfo recoverUser() {
        try {
            FileInputStream fos = this.openFileInput(apiConfig.user_file_name);
            ObjectInputStream oinput;
            oinput = new ObjectInputStream(fos);
            UserInfo user = (UserInfo) oinput.readObject();
            fos.close();
            oinput.close();
            Log.i(TAG, "recover user success!");
            Log.i(TAG, user.toString());
            return user;
        } catch (Exception e) {
            Log.i(TAG, "recover user failed!");
            e.printStackTrace();
        }
        return null;
    }

    public void saveUser(UserInfo user) {
        try {
            FileOutputStream fos = this.openFileOutput(apiConfig.user_file_name,
                    Context.MODE_PRIVATE);
            ObjectOutputStream oout = null;
            oout = new ObjectOutputStream(fos);
            oout.writeObject(user);
            fos.close();
            oout.close();
            Log.i(TAG, "save user success!");
        } catch (Exception e) {
            Log.i(TAG, "save user failed!");
            e.printStackTrace();
        }
    }

    public void clearUser() {
        try {
            FileOutputStream fos = this.openFileOutput(apiConfig.user_file_name,
                    Context.MODE_PRIVATE);
            ObjectOutputStream oout = null;
            oout = new ObjectOutputStream(fos);
            oout.writeObject(null);
            fos.close();
            oout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public List<EvaluateGradle> getGradleList() {
//        return gradleList;
//    }

    //List<EvaluateGradle> gradle,
    public void saveEvaluateGradle(String jsonArray) {
//        try {
//            this.gradleList = gradle;
//            FileOutputStream fos = this.openFileOutput(apiConfig.evaluate_gradle_file_name,
//                    Context.MODE_PRIVATE);
//            ObjectOutputStream oout = null;
//            oout = new ObjectOutputStream(fos);
//            oout.writeObject(gradle);
//            fos.close();
//            oout.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        SharedPreferences sharedPreferences = getSharedPreferences("evaluate_gradle", Context.MODE_PRIVATE); //私有数据
        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
        editor.putString("evaluate_start", jsonArray);
        editor.commit();
    }
    public List<EvaluateGradle> getEvaluateGradle(){
        List<EvaluateGradle> gradles=new ArrayList<>();
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("evaluate_gradle", 0x0001);
        String evaluate_start = sharedPreferences.getString("evaluate_start","");
        if(!AbStrUtil.isEmpty(evaluate_start)){
            gradles= AbJsonUtil.fromJson(evaluate_start,new TypeToken<ArrayList<EvaluateGradle>>(){});
        }
        if(gradles!=null&&gradles.size()>0){
            Log.e(TAG,"缓存评分=="+gradles.toString());
            return  gradles;
        }else
            return null;
    }

//    public void clearEvaluate() {
//        try {
//            FileOutputStream fos = this.openFileOutput(apiConfig.evaluate_gradle_file_name,
//                    Context.MODE_PRIVATE);
//            ObjectOutputStream oout = null;
//            oout = new ObjectOutputStream(fos);
//            oout.writeObject(null);
//            fos.close();
//            oout.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    List<ProvinceModel> provinceList;


    public List<ProvinceModel> getProvinceList() {
        return provinceList;
    }

    public void saveProvinceList(List<ProvinceModel> province) {
        try {
            this.provinceList = province;
            FileOutputStream fos = this.openFileOutput("province.dat",
                    Context.MODE_PRIVATE);
            ObjectOutputStream oout = null;
            oout = new ObjectOutputStream(fos);
            oout.writeObject(provinceList);
            fos.close();
            oout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
